﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;
using Edge.Business.Domain.Application;
using Edge.Common.Services;
using Edge.Common.Utils;
using Edge.WebCode;
using log4net;
using Shop.Business.Domain.Customers;
using Shop.Web.AppCode.AjaxHandlers;

namespace Shop.Web.AppCode
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class AjaxHandler : IHttpHandler, IRequiresSessionState
    {
        #region Logger

        protected static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        #endregion

        public const String BREAK = "&lt;br&gt;";
        public const String ACCESS_DENIED_MESSAGE = "{}";
        String js = String.Empty;
        private static Dictionary<string, Type> handlersMap = new Dictionary<string, Type>();

        static AjaxHandler()
        {
            #region fill handlersMap

            foreach (var type in typeof(AjaxHandler).Assembly.GetTypes())
            {
                var attribure = ReflectionUtils.GetFirstAttribure<HandlerAttribute>(type, true);
                if (attribure == null)
                    continue;

                string name = type.Name;
                if (!StringUtils.IsBlankOrNull(attribure.name))
                    name = attribure.name;

                handlersMap[name] = type;
            }

            #endregion
        }


        #region IHttpHandler Members

        public void ProcessRequest(HttpContext context)
        {
            HttpContext.Current.Response.Cache.SetExpires(DateTime.Now);
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
            HttpContext.Current.Response.Cache.SetNoStore();
            HttpContext.Current.Response.AppendHeader("Pragma", "no-cache");
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Expires = -1500;
            HttpContext.Current.Response.CacheControl = "no-cache";
            HttpContext.Current.Response.Charset = "utf-8";

            String content = context.Request.QueryString["content"];

            if (String.IsNullOrEmpty(content))
                return;

            string contentType = "text/javascript";

//            if (BasePage.CurrentUser != null || content == "AutoLogoutLogin")
//            {
                BaseHandler handler = GetHandler(content);
                js = handler != null ? handler.ProcessRequest(context) : BaseHandler.JsonError("Нет такого файлика (");
//                if (content != "AutoLogout" && content != "LockedRecord")
//                {
//                    HttpContext.Current.Session[BasePage.LAST_ACTIVE] = DateTime.Now;
//                }
//            }
//            else
//            {
//                log.Error("Access Denied. Request URL: " + context.Request.Url + ".");
//                js = BaseHandler.JsonError("Access Denied!");
//            }

            context.Response.ContentType = contentType;
            context.Response.Write(js);
        }

        private BaseHandler GetHandler(string content)
        {
            if (!handlersMap.ContainsKey(content))
                return null;
            var instance = Activator.CreateInstance(handlersMap[content]);
            return (BaseHandler)instance;
        }

        public bool IsReusable
        {
            get { return false; }
        }

        private bool CheckPermission(PermissionType id)
        {
//            var holder = Locator.GetService<IContextObjects>().Get<CustomerHolder>();
//            if (holder == null || holder.Object == null || !holder.Object.HavePermission(id))
//            {
//                js = BaseHandler.JsonError("Access Denied!");
//                return false;
//            }
            return true;
        }


        #endregion
    }
}
